<template>
  <div class="merchant-center-container">
    <!-- 商家信息展示 -->
    <el-card v-if="merchantInfo.merchantId" class="merchant-info-card">
      <template #header>
        <div class="card-header">
          <span>商家信息</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="info-item">
            <span class="label">商家ID:</span>
            <span class="value">{{ merchantInfo.merchantId }}</span>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="info-item">
            <span class="label">商家名称:</span>
            <span class="value">{{ merchantInfo.name }}</span>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="info-item">
            <span class="label">手机号:</span>
            <span class="value">{{ merchantInfo.phone }}</span>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="info-item">
            <span class="label">地址:</span>
            <span class="value">{{ merchantInfo.address }}</span>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="info-item">
            <span class="label">所属区域:</span>
            <span class="value">{{ getRegionName(merchantInfo.regionId) }}</span>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="info-item">
            <span class="label">合作状态:</span>
            <span class="value">
              <el-tag :type="getCooperationStatusType(merchantInfo.cooperationStatus)">
                {{ formatCooperationStatus(merchantInfo.cooperationStatus) }}
              </el-tag>
            </span>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="info-item">
            <span class="label">合作期限:</span>
            <span class="value">{{ merchantInfo.cooperationTerm }}</span>
          </div>
        </el-col>
      </el-row>
      
      <div class="button-group">
        <el-button type="primary" @click="handleUpdate">修改信息</el-button>
      </div>
    </el-card>
    
    <!-- 无数据提示 -->
    <el-empty v-else description="暂无商家信息" />
    
    <!-- 修改商家信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="merchantRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <!-- 合作状态只读显示 -->
        <el-form-item label="合作状态">
          <el-tag :type="getCooperationStatusType(form.cooperationStatus)">
            {{ formatCooperationStatus(form.cooperationStatus) }}
          </el-tag>
        </el-form-item>
        <!-- 合作期限只读显示 -->
        <el-form-item label="合作期限">
          <span>{{ form.cooperationTerm }}</span>
        </el-form-item>
        <el-form-item label="所属区域" prop="regionId">
          <el-select v-model="form.regionId" placeholder="请选择所属区域" clearable style="width: 100%">
            <el-option
              v-for="region in regionList"
              :key="region.regionId"
              :label="region.name"
              :value="region.regionId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getCurrentInstance } from 'vue'
import { listRegion } from "@/api/manage/region"
import { getMerchantByUserId, updateMerchant } from "@/api/manage/merchant"
import { getUserId } from "@/api/manage/center"

const { proxy } = getCurrentInstance()
const { merchant_status } = proxy.useDict('merchant_status')

// 响应式数据
const open = ref(false)
const title = ref("")
const regionList = ref([])
const merchantInfo = ref({})
const userId = ref(null)

// 表单数据
const form = ref({})
const rules = ref({
  name: [
    { required: true, message: "商家名称不能为空", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  address: [
    { required: true, message: "地址不能为空", trigger: "blur" }
  ],
  regionId: [
    { required: true, message: "所属区域不能为空", trigger: "blur" }
  ]
})

// 获取区域列表
function getRegionList() {
  listRegion({}).then(response => {
    regionList.value = response.rows || []
  }).catch(err => {
    console.error('获取区域列表失败:', err)
    proxy.$modal.msgError("获取区域列表失败")
  })
}

// 根据区域ID获取区域名称
function getRegionName(regionId) {
  const region = regionList.value.find(item => item.regionId === regionId)
  return region ? region.name : ''
}

// 格式化合作状态
function formatCooperationStatus(status) {
  const statusDict = merchant_status.value.find(dict => parseInt(dict.value) === status)
  return statusDict ? statusDict.label : '未知状态'
}

// 根据合作状态值获取标签类型
function getCooperationStatusType(status) {
  switch (status) {
    case 1: // 合作中
      return 'success'
    case 2: // 合作中断
      return 'warning'
    case 3: // 合作过期
      return 'danger'
    default:
      return 'info'
  }
}

// 获取当前用户ID
function getCurrentUserId() {
  return new Promise((resolve, reject) => {
    getUserId().then(response => {
      // 根据 goods.vue 中的逻辑，后端传来的数据是只有 userId
      if (typeof response === 'number') {
        userId.value = response
        resolve(response)
      } else if (response && response.userId) {
        userId.value = response.userId
        resolve(response.userId)
      } else if (response.code === 200 && response.rows && response.rows.length > 0) {
        userId.value = response.rows[0].userId
        resolve(response.rows[0].userId)
      } else {
        reject(new Error('无法获取用户ID'))
      }
    }).catch(error => {
      console.error('获取用户ID失败:', error)
      proxy.$modal.msgError("获取用户ID失败")
      reject(error)
    })
  })
}

// 根据用户ID获取商家信息
function getMerchantInfoByUserId() {
  if (!userId.value) return
  
  getMerchantByUserId(userId.value).then(response => {
    if (response.code === 200 && response.data) {
      merchantInfo.value = response.data
    } else {
      proxy.$modal.msgWarning("暂无商家信息")
    }
  }).catch(err => {
    console.error('获取商家信息失败:', err)
    proxy.$modal.msgError("获取商家信息失败")
  })
}

// 修改按钮操作
function handleUpdate() {
  form.value = { ...merchantInfo.value }
  open.value = true
  title.value = "修改商家信息"
}

// 提交表单
function submitForm() {
  proxy.$refs["merchantRef"].validate(valid => {
    if (valid) {
      updateMerchant(form.value).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          // 更新页面显示的信息
          merchantInfo.value = { ...form.value }
        } else {
          proxy.$modal.msgError("修改失败: " + (response.msg || ""))
        }
      }).catch(err => {
        console.error('修改商家信息失败:', err)
        proxy.$modal.msgError("修改失败")
      })
    }
  })
}

// 取消操作
function cancel() {
  open.value = false
  proxy.resetForm("merchantRef")
}

// 组件挂载时执行
onMounted(() => {
  getRegionList()
  getCurrentUserId().then(() => {
    getMerchantInfoByUserId()
  }).catch((error) => {
    console.error('初始化失败:', error)
    proxy.$modal.msgError("页面初始化失败")
  })
})
</script>

<style scoped>
.merchant-center-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.merchant-info-card {
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.info-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.info-item:hover {
  background-color: #f0f0f0;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
}

.label {
  width: 120px;
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.button-group {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .merchant-info-card {
    margin: 0 10px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>